// modal.js

import { createVNode, render as vueRender } from "vue";
import { ElCheckbox } from "element-plus";

/**
 * @param {import("vue").DefineComponent} content
 * @param {import("vue").Prop} props
 * @param {Omit<import("ant-design-vue").ModalProps, 'visible'>} config
 */
export  function ModalFc(content, props, config) {
  const container = document.createDocumentFragment() as any;
  const _contentVnode = createVNode(content, props);
  const metadata = Object.create({
    okText: "确定",
    cancelText: "取消",
    visible: true,
    ...config,
  });

  metadata.onCancel = async function (...arg) {
    await config.onCancel?.(...arg);
    close();
  };

  metadata.onOk = async function () {
    if (!(config.onOk instanceof Function)) {
      close();
      return;
    }
    const result = config.onOk();
    if (!(result instanceof Promise)) {
      close();
      return;
    }
    update({ confirmLoading: true });
    return result
      .then(() => {
        update({ confirmLoading: false });
        close();
      })
      .catch(() => {
        update({ confirmLoading: false });
      });
  };
  let vm = createVNode(ElCheckbox, metadata, () => _contentVnode);
  /**
   *
   * @param {typeof config} config
   */
  function update(config) {
    Object.assign(vm.component.props, config);
    vm.component.update();
  }
  function close() {
    metadata.visible = false;
    destroy()
    update(metadata);
    
  }
  function destroy() {
    if (vm) {
      vueRender(null, container);
      vm = null;
    }
  }
  vueRender(vm, container);
  return {
    ..._contentVnode,
    close,
    destroy,
    update,
  };
}
